using B.S.NewMedical.Api.Write.Application.Command.Order.Register;
using B.S.NewMedical.Domain.Order;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Write.Application.Handler.Order.Register
{
    /// <summary>
    /// 批量删除挂号处理器
    /// </summary>
    public class BatchDeleteRegisterCommandHandle : IRequestHandler<BatchDeleteRegisterCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<RegisterModel> _registerRepository;
        private readonly ILogger<BatchDeleteRegisterCommandHandle> _logger;

        public BatchDeleteRegisterCommandHandle(
            IBaseRepository<RegisterModel> registerRepository,
            ILogger<BatchDeleteRegisterCommandHandle> logger)
        {
            _registerRepository = registerRepository;
            _logger = logger;
        }

        public async Task<ApiResult<int>> Handle(BatchDeleteRegisterCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            try
            {
                _logger.LogInformation("开始批量删除挂号记录，数量：{Count}", request.RegisterIds.Count);

                // 1. 查找要删除的挂号记录
                var registers = _registerRepository.GetAll()
                    .Where(x => request.RegisterIds.Contains(x.Id) && !x.IsDeleted)
                    .ToList();

                if (registers == null || registers.Count == 0)
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "未找到要删除的挂号记录";
                    _logger.LogWarning("未找到要删除的挂号记录，IDs：{Ids}", 
                        string.Join(",", request.RegisterIds));
                    return result;
                }

                // 2. 检查是否有已完成的挂号记录
                var completedRegisters = registers
                    .Where(x => !string.IsNullOrEmpty(x.Orderstatus) && 
                               x.Orderstatus.Equals("已完成", StringComparison.OrdinalIgnoreCase))
                    .ToList();

                if (completedRegisters.Any())
                {
                    var completedIds = string.Join(",", completedRegisters.Select(x => x.Id));
                    result.Code = ApiEnum.Fail;
                    result.Msg = $"以下挂号记录已完成，不能删除：{completedIds}";
                    _logger.LogWarning("尝试删除已完成的挂号记录，IDs：{Ids}", completedIds);
                    return result;
                }

                // 3. 检查是否有已就诊的挂号记录
                var visitedRegisters = registers
                    .Where(x => !string.IsNullOrEmpty(x.Orderstatus) && 
                               x.Orderstatus.Equals("已就诊", StringComparison.OrdinalIgnoreCase))
                    .ToList();

                if (visitedRegisters.Any())
                {
                    var visitedIds = string.Join(",", visitedRegisters.Select(x => x.Id));
                    result.Code = ApiEnum.Fail;
                    result.Msg = $"以下挂号记录已就诊，不能删除：{visitedIds}";
                    _logger.LogWarning("尝试删除已就诊的挂号记录，IDs：{Ids}", visitedIds);
                    return result;
                }

                // 4. 检查是否有已确认的挂号记录
                var confirmedRegisters = registers
                    .Where(x => !string.IsNullOrEmpty(x.Orderstatus) && 
                               x.Orderstatus.Equals("已确认", StringComparison.OrdinalIgnoreCase))
                    .ToList();

                if (confirmedRegisters.Any())
                {
                    var confirmedIds = string.Join(",", confirmedRegisters.Select(x => x.Id));
                    result.Code = ApiEnum.Fail;
                    result.Msg = $"以下挂号记录已确认，不能删除：{confirmedIds}";
                    _logger.LogWarning("尝试删除已确认的挂号记录，IDs：{Ids}", confirmedIds);
                    return result;
                }

                // 5. 执行批量逻辑删除
                var currentTime = DateTime.Now;
                foreach (var register in registers)
                {
                    register.IsDeleted = true;
                    register.UpdateTime = currentTime;
                }

                // 6. 批量更新数据库
                var updateResult = await _registerRepository.UpdateRangAsync(registers);

                if (updateResult > 0)
                {
                    result.Code = ApiEnum.Success;
                    result.Msg = $"成功删除 {updateResult} 条挂号记录";
                    result.Data = updateResult;
                    
                    _logger.LogInformation("批量删除挂号记录成功，数量：{Count}，IDs：{Ids}", 
                        updateResult, string.Join(",", request.RegisterIds));
                }
                else
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "批量删除挂号记录失败";
                    result.Data = updateResult;
                    
                    _logger.LogError("批量删除挂号记录失败，IDs：{Ids}", 
                        string.Join(",", request.RegisterIds));
                }
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Error;
                result.Msg = $"批量删除挂号记录时发生异常：{ex.Message}";
                
                _logger.LogError(ex, "批量删除挂号记录时发生异常，IDs：{Ids}，异常信息：{Message}", 
                    string.Join(",", request.RegisterIds), ex.Message);
            }

            return result;
        }
    }
} 